<!--
  ~ Copyright 2010 Pierre Heinzerling, Uwe Janner, Patrick Wright
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~        http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
    <script type="text/javascript" src="js/toolinsky-server.js"></script>
    <script type="text/javascript" src="js/util.js"></script>
    <script type="text/javascript" src="js/local-storage.js"></script>

    <script type="text/javascript">
        // tracks the themes that are modified, as picked up by polling. will be null if there are none.
        var themes_modified;

        function logMessage(msg) {
            log.push(msg);
        }

        function maybePollForNotifications() {
            if (lsGetOptionsPollingEnabled()) {
                if (!themes_modified) {
                    pollForNotifications();
                }
            } else {
                setTimeout(function() {maybePollForNotifications()}, (10 * 1000));
            }
        }

        function pollForNotifications() {
            var pts = lsGetOptionsPollingTimeSec();
            writeLog("poll for notifications (every " + pts + " sec)");
            setTimeout(function() {
                serverListModifiedThemes(function(themes) {
                    if (themes && themes.length > 0) {
                        themes_modified = themes;
                        chrome.browserAction.setBadgeText({text: ":-:"});
                    }
                });
                maybePollForNotifications();
            }, (pts * 1000));
        }

        function clearPendingNotifications() {
            themes_modified = null;
            chrome.browserAction.setBadgeText({text: ""});
            maybePollForNotifications();
        }

        function havePendingNotification() {
            return themes_modified;
        }

        function listModifiedThemes() {
            return themes_modified;
        }

        function showOverview(theme, content) {

			chrome.tabs.getAllInWindow(null, function (tabs) {
				var found;
				var fileName;
				for (var i = 0; i < tabs.length; i++) {
					var tab = tabs[i];
					fileName = tab.url.substring(tab.url.lastIndexOf("/") + 1);
					if (fileName == "overview_page.html?id=" + theme.key.id) {
						chrome.tabs.update(tab.id, {selected:true}, function(tab) {
			                chrome.extension.sendRequest({type: "links_refresh", theme: JSON.stringify(theme), content: JSON.stringify(content)}, function(response) {
			                });
			            });
						found = true;
						break;
					}
				}
				if (!found) {
					chrome.tabs.create({url: "overview_page.html?id=" + theme.key.id, selected: false}, function(tab) {
		                chrome.extension.sendRequest({type: "links", theme: JSON.stringify(theme), content: JSON.stringify(content)}, function(response) {
		                });
		            });
				}
			});
        }

        function refreshOverview(tabId, themeId) {
            var links = new Array();
            serverGetTheme(null, themeId, function(themeAndInvitation) {
                var theme = themeAndInvitation.theme;
                serverListLinksForTheme(themeId, function (ln, cmt) {
                    links.push({link: ln, comments: cmt});
                }, function(howMany) {
                    chrome.extension.sendRequest({type: "links_refresh", themeId: themeId.toString(), theme: JSON.stringify(theme), content: JSON.stringify(links)}, function(response) {
                    });
                });
            })
        }

        function writeLog(msg) {
            console.log(msg);
            chrome.extension.sendRequest({msg: msg}, function(response) {
            });
        }

        function initialLogin() {
            if (!loginState.email) {
                loginState.login();
            }
        }

		function getConfiguration(){
			extensionConfig = window.localStorage['extensionConfig'];
			if( !extensionConfig ){
				extensionConfig = setConfiguration( {} );
			}
			return extensionConfig;
		}

		function setConfiguration( newConfig ){
			window.localStorage['extensionConfig'] = newConfig;
			return newConfig;
		}

        var log = new Array();

        var loginState = {
            email: null,
            logoutUrl: null,
            toggleIcon: function() {
                var imgPath = "icons/arrow_" + (loginState.email ? "" : "not") + "in.png";
                chrome.browserAction.setIcon({ path: imgPath});
            },
            loginTabId: null,
            prepareLoginPage:
                    function(tab) {
                        loginState.loginTabId = tab.id;
                    },
            login: function() {
                chrome.tabs.create({url: loginState.loginUrl, selected: true}, function() {
                });
            },
            logout: function() {
                chrome.tabs.create({url: loginState.logoutUrl, selected: true}, function() {
                });
            },
            init: function(callback) {
                $.ajax({
                    url: TOOLINSKY_GAE_HOST + '/auth/status',
                    dataType: 'json',
                    data: {},
                    success:
                            function(data) {
                                console.log("Returned from calling auth/status with email=" + data.email + " was: " + loginState.email);
                                if (loginState.email != data.email) {
                                    eventManager.trigger("loginStateChanged", data.email);
                                }
                                loginState.email = data.email;
                                // if we are in local mode we have to prepend the localhost address:
                                loginState.logoutUrl = data.logoutUrl.indexOf("http") == 0 ? data.logoutUrl : TOOLINSKY_GAE_SERVER + data.logoutUrl;
                                loginState.loginUrl = data.loginUrl.indexOf("http") == 0 ? data.loginUrl : TOOLINSKY_GAE_SERVER + data.loginUrl;
                            },
                    error:
                            function(XMLHttpRequest, textStatus, errorThrown) {
                                console.log("AuthStatusError: " + textStatus + ", " + errorThrown);
                            },
                    complete: function(XMLHttpRequest, textStatus) {
                        loginState.toggleIcon();
                        if (callback) callback(loginState.email);
                    }
                });
                loginState.loggedIn = true;
                loginState.toggleIcon();
                serverGetThemeScratchpad(loginState.email, function(theme) {
                    lsStoreCurrentTheme(theme);
                });
            }
        }

        var eventManager = {
            listeners: new Array(),
            registerLoginStateChanged: function(listener) {
                console.log("welcome new listener of type " + typeof(listener) + ": " + listener);
                eventManager.listeners.push(listener);
            },
            trigger: function(event, data) {
                for (var ii = 0; ii < eventManager.listeners.length; ii++) {
                    var callback = eventManager.listeners[ii];
                    console.log("notify listener of type " + typeof(callback) + ": " + callback);
                    callback.call(event, data);
                }
            }
        }

        chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
            if (request.selection) {
                //{url: window.location.href.toString(), selection: window.getSelection().toString(), key: evt.keyIdentifier},
                sendResponse({message: "Thank You: " + request.url + " " + request.selection});
                chrome.browserAction.setBadgeText({text: "+"});
                chrome.tabs.getSelected(null, function(tab) {
                    serverSubmitLink(lsGetCurrentTheme().key.id, request.url, tab.title, request.selection, "", "", function() {
                        setTimeout(function() {
                            chrome.browserAction.setBadgeText({text: ""});
                        }, 500);
                    });
                });
            } else if (request.authPageLoaded && sender.tab) {
                // remove the unnecessary tab:
                chrome.tabs.remove(sender.tab.id);
                // refresh loginState:
                loginState.init();
            } else if (request.getHotKey) {
                // give back hotKey:
				if( loadHotkeyConfig( ) )
                	sendResponse( {
						message: loadHotkeyConfig()
					} );
            } else if (request.log) {
                logMessage(request.log);
            } else if (request.refreshOverview) {
                sendResponse({message: "will do"});
                refreshOverview(sender.tab.id, request.themeId);
            }
        });

        // log table
        var logTabId;

		// extension config values:
		var extensionConfig;

        /* used for debugging only
        chrome.tabs.create({url: "log_page.html", selected: false}, function(tab) {
            logTabId = tab.id;
        });*/

        console.log("Initializing the Extension, staring with call to auth/status");
        loginState.init(initialLogin);

        //
        //  polling
        //
        maybePollForNotifications();

    </script>
</head>
</html>
